import {
  HTTP
} from '../utils/http.js';

import {
  enums
} from '../utils/enums';

class KeywordModel extends HTTP {

  key = 'q';
  maxLength = 10;

  getHistory() {
    const words = wx.getStorageSync(this.key);
    if (!words) {
      return [];
    }
    return words;
  }

  /**
   * 获取热搜词
   */
  getHot() {
    return this.request({
      url: 'hot/words'
    }).then(res => {
      wx.setStorageSync(enums.hot, res.data);
    });
  }

  /**
   * 添加到搜索历史
   * @param {String} keyword 
   */
  addToHistory(keyword) {
    let words = this.getHistory();
    const has = words.includes(keyword);
    if (!has) {
      const length = words.length;
      if (length >= this.maxLength) {
        words.pop();
      }
      words.unshift(keyword);
      wx.setStorageSync(this.key, words);
    }
  }

  /**
   * 清除历史搜索
   */
  clearHistory() {
    wx.setStorageSync(this.key, new Array());
  }
}

export {
  KeywordModel
}